﻿#region Usings

using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization;

#endregion

namespace Rail.Net.Core.Model.Nonpersistent
{
    [Serializable]
    [DataContract]
    public class TransportPlanModel
    {
        private List<ContengentTrainModel> _contengentTrains;

        public TransportPlanModel(List<ConnectionModel> connections)
        {
            Connections = connections;
        }

        [DataMember]
        public List<ConnectionModel> Connections { get; set; }

        public bool IsDomesticOnly
        {
            get { return Connections.All(c => c.IsDomesticOnly); }
        }

        [DataMember]
        public List<ContengentTrainModel> ContengentTrains
        {
            get
            {
                if (_contengentTrains == null)
                {
                    var result = new List<ContengentTrainModel>();
                    foreach (var connection in Connections.Where(c => c.IsValid))
                    {
                        var contTrain = connection.ContengentTrain;
                        if (contTrain == null)
                            continue;
                        Relation relation = null;
                        var domesticDistance = connection.DomesticSequences[0].DistanceModel.DistanceKmSum;

                        // build the key
                        var key = "";
                        if (connection.IsDomesticOnly)
                        {
                            key += "d=" + domesticDistance + ";";
                        }
                        else
                        {
                            relation = connection.InternationalSequences[0].Relation;
                            if (relation == null)
                            {
                                continue;
                            }

                            var borderEva = relation.BorderStation;
                            key += "d=" + domesticDistance + ";" + "r=" + relation.RelationNumber + ";b=" + borderEva + ";";
                            key = relation.RelationRus.Aggregate(key, (current, ru) => current + (ru.Ru.Code + "=" + ru.Distance + ";"));
                        }
                        var contengent = result.FirstOrDefault(c => c.Key == key && c.Connections.Count < 10) ?? new ContengentTrainModel(key, domesticDistance, relation);
                        contengent.Connections.Add(connection);

                        if (!result.Contains(contengent))
                        {
                            result.Add(contengent);
                        }
                    }
                    _contengentTrains =  result;
                }
                return _contengentTrains;
            }
        }
    }
}